package demo.service.impl;

import demo.common.SelectOption;
import demo.model.Student;
import demo.repository.CollegeRepository;
import demo.repository.StudentRepository;
import demo.service.StudentService;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.server.ResponseStatusException;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class StudentServiceImpl implements StudentService {
    private final CollegeRepository collegeRepository;
    private final StudentRepository repository;

    public StudentServiceImpl(CollegeRepository collegeRepository, StudentRepository repository) {
        this.collegeRepository = collegeRepository;
        this.repository = repository;
    }

    @Override
    public Page<Student> findAll(Pageable pageable) {
        return repository.findAll(pageable);
    }

    @Override
    public Student findById(Long id) {
        return repository.findById(id).orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "cannot found by id: " + id));
    }

    @Override
    public Student add(Student s) {
        return repository.save(s);
    }

    public Student update(Student s) {
        // 数据库中已有学生，使用原来的照片
        repository.findById(s.getId()).ifPresent((os) -> s.setPhoto(os.getPhoto()));
        return repository.save(s);
    }

    @Override
    public Student delete(Long id) {
        Student s = findById(id);
        repository.delete(s);
        return s;
    }

    public Student setPhoto(Long id, MultipartFile file) {
        try {
            Student s = findById(id);
            s.setPhoto(file.getBytes());
            repository.save(s);
            return s;
        } catch (IOException e) {
            throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "上传照片失败: " + id);
        }
    }

    @Override
    public byte[] getPhoto(Long id) {
        Student s = findById(id);
        return s.getPhoto();
    }

    public HashMap<String, Object> getSelectData() {
        HashMap<String, Object> selectData = new HashMap<>();

        var list = collegeRepository.findAll();
        List<SelectOption> parentIdList = list.stream()
                .map(item -> new SelectOption(item.getName(), item.getId()))
                .collect(Collectors.toList());
        selectData.put("collegeId", parentIdList);

        return selectData;
    }
}
